<template>
  <div>
    <Row style="margin-bottom: 10px;padding-left: 5px">
      <Col span="12">
        <span style="font-size: 18px;font-weight: bold">{{container.matchName}}</span>
        <span v-if="container.kindCode">(<dict-span  class="p-info" code="ZGX_SSDJ" :value="container.kindCode"></dict-span>)</span>
        <span style="margin-left: 10px;font-size: 16px">共<span style="color: #2d8cf0;font-size: 18px">{{container.countNum || 0}}</span>人报名</span>
      </Col>
      <Col span="12">
        <div style="float: right;padding-right: 5px;font-size: 16px;line-height: 28px">
          <span v-text="$moment(container.startTime).format('YYYY-MM-DD')"></span>
          至
          <span v-text="$moment(container.endTime).format('YYYY-MM-DD')"></span>
          进行比赛
        </div>
      </Col>
    </Row>
    <Card style="margin-bottom: 20px">
      <Row>
        <Form ref='model' :model="model" label-position="right" inline :label-width='100'>
          <Row>
            <Col span="6">
              <FormItem prop="payStatus" label="缴费状态">
                <Select v-model="model.payStatus" class="search-col" clearable style="width: 200px">
                  <Option v-for="item in payStatusColums":value="item.key" :key="`search-col-${item.key}`">{{ item.title }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem prop="retreatStatus" label="是否退费" v-show="type==='money-detail'||type === 'event-person'">
                <Select v-model="model.retreatStatus" class="search-col" clearable style="width: 200px">
                  <Option v-for="item in retreatStatusColums" :value="item.key" :key="`search-col-${item.key}`">{{ item.title }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem prop="banSatus" label="是否禁赛" v-show="type==='suspension-detail'||type === 'event-person'">
                <Select v-model="model.banSatus" class="search-col" clearable style="width: 200px">
                  <Option v-for="item in jinsaiStatusColums" :value="item.key" :key="`search-col-${item.key}`">{{ item.title }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Button @click="search" type="primary" class="m-l-sm" icon="md-search">筛选</Button>
            <Button @click="reset" class="m-l-sm" icon="md-sync">重置</Button>
            <Button @click="exportExcel" type="primary" class="m-l-sm">导出</Button>
          </Row>
        </Form>
      </Row>
    </Card>
    <Card v-if="container.matchName && type !== 'event-person'">
      <div v-show="container.kindCode">
        <Table :loading="loading" :columns="tableColumn" stripe border :data="resultData"></Table>
      </div>
      <Tabs v-show="!container.kindCode" :value="tabValue">
          <TabPane label="男子组" name="boy">
            <Table :loading="loading" :columns="tableColumn" stripe border :data="boyData"></Table>
          </TabPane>
          <TabPane label="女子组" name="girl">
            <Table :loading="loading" :columns="tableColumn" stripe border :data="girlData"></Table>
          </TabPane>
      </Tabs>
    </Card>
    <Card v-if="container.matchName && type === 'event-person'">
      <Tabs :value="showList" @on-click="tabClick"	>
        <TabPane label="申请列表" name="apply">
            <Table :loading="loading" :columns="tableColumn" stripe border :data="resultData"></Table>
        </TabPane>
        <TabPane label="审核列表" name="agree">
          <Row style="text-align: right">
            <Button type="primary" style="text-align: right;margin-bottom: 20px" @click="configGo">配置出发行程</Button>
          </Row>
            <Table :loading="loading" :columns="agreeColumn" stripe border :data="resultData" @on-selection-change="selectChange"></Table>
        </TabPane>
        <TabPane label="出发表" name="goForm">
          <Row style="text-align: right">
            <Button type="primary" style="text-align: right;margin-bottom: 10px" @click="exportGo">出发表导出</Button>
          </Row>
          <RadioGroup v-model="session" @on-change="changeSession"	style="margin-bottom: 20px">
            <Radio label="0" style="margin-right: 20px;font-size: 14px;font-weight: bold">第一轮</Radio>
            <Radio label="1" style="margin-right: 20px;font-size: 14px;font-weight: bold">第二轮</Radio>
            <Radio label="2" style="margin-right: 20px;font-size: 14px;font-weight: bold">第三轮</Radio>
          </RadioGroup>
          <v-table
            is-horizontal-resize
            is-vertical-resize
            :columns="sessionColumns"
            :table-data="formResult"
            even-bg-color="#f4f4f4"
            row-hover-color="#eee"
            row-click-color="#edf7ff"
            style="width:100%"
            :is-loading="sessionLoading"
            @on-custom-comp="del"
            :cell-merge="handleSpan"
          ></v-table>
        </TabPane>
      </Tabs>
    </Card>
    <Modal v-model="visible" width='400' title="缴费凭证">
      <Upload
        type="drag"
        ref="upload"
        :format="['jpg','jpeg','png']"
        action="/pub/configure/uploadFile"
        :on-success="getFieldData"
      >
        <div style="padding: 20px">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>点击上传</p>
        </div>
      </Upload>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button @click="save" class="m-l-md" type="primary">确认</Button>
      </div>
    </Modal>
    <departure-schedule :visible.sync="isSchedule" :memberArr="member" :matchId="$route.params.id" @upload="queryList"></departure-schedule>
  </div>
</template>

<script>
  import { queryListByMatchId,getOne,exportEnrollExcel,updateBanStatus,updatePayStatus,updateRetreatStatus,updatePayUrl,approvalEnrollStaff,excel,queryForm,deleteGroup } from '@/api/applets'
  import dictSpan from '_c/dict/dict-span.vue';
  import departureSchedule from './components/departureSchedule/departureSchedule'
  import {payStatusColums,retreatStatusColums,jinsaiStatusColums}from '@/libs/util.js'
  import Tables from "../../components/tables/tables";
  export default {
    components: {
      Tables,
      dictSpan,
      departureSchedule,
    },
    data() {
      return {
        loading: false,
        visible:false,
        container:{},
        tabValue:'boy',
        showList:'apply',
        session:'0',
        isSchedule:false,
        model: {
          matchId:null,
          payStatus: '',
          retreatStatus:'',
          banSatus:'',
          pageNo: 1,
          pageSize: 10,
          type:''
        },
        payStatusColums:payStatusColums,
        retreatStatusColums:retreatStatusColums,
        jinsaiStatusColums:jinsaiStatusColums,
        boyData:[],
        girlData:[],
        resultData:[],
        baseColumn:[
          {
            title: "序号",
            width: 80,
            align: "left",
            render: (h, params) => {
              return h(
                "span",
                this.model.pageSize * (this.model.pageNo - 1) + params.index + 1
              );
            }
          },
          {
            title: '姓名',
            key: 'staffName'
          },
          {
            title: '身份',
            render: (h, params) => {
              return h("span",params.row.isVip === '1'?'会员':'非会员')
            }
          },
          {
            title: '国籍',
            key: 'country',
            render: (h, params) => {
              return h(dictSpan, {
                props: {
                  code: 'AG_OUT',
                  value: params.row.country
                }
              });
            }
          },
          {
            title: '会员类型',
            key: 'cardTypeName',
            render:(h,params)=> {
              return h('span', params.row.cardTypeName || '-');
            }

          },
          {
            title: '会员编码',
            key: 'certificateNo',
            render:(h,params)=> {
              return h('span', params.row.certificateNo || '-');
            }
          },
          {
            title: '参赛费用',
            key: 'matchMoney',
            render:(h,params)=> {
              return h('span', params.row.matchMoney/100+'元');
            }
          },
          {
            title: '缴费状态',
            key: 'payStatus',
            render: (h, params) => {
                  return h('span',  params.row.payStatus === '1' ? '已缴费' : '未缴费');
                }
          },
          {
            title: '缴费凭证',
            key: 'payUrl',
            render: (h, params) => {
              let devicesArr = [];
              let photo = [params.row.payUrl];
              if(params.row.payUrl&&params.row.payStatus ==='1') {
                devicesArr.push(
                  h('Tooltip', {
                    props: {
                      trigger: 'hover',
                      placement: 'top',
                      content: '缴费凭证'
                    }
                  }, [
                    h('viewer', {
                      props:{
                        images:photo
                      }
                    }, [
                      h('img', {
                        attrs: {
                          src:photo[0],
                          style: 'width: 80px;height:80px'
                        },
                      })
                    ])
                  ])
                );
              }
              return h('div', devicesArr.length > 0?devicesArr:'暂无数据');
            }
          },
          {
            title: '是否退费',
            key: 'retreatStatus',
            render: (h, params) => {
              return h('span',  params.row.retreatStatus === '1' ? '已退费' : '未退费');
            }
          },
          {
            title: '是否禁赛',
            key: 'banSatus',
            render: (h, params) => {
              return h('span',  params.row.banSatus === '1' ? '已禁赛' : '未禁赛');
            }
          },
          {
            title: '报名状态',
            key: 'status',
            render: (h, params) => {
              return h('span',  params.row.status === '1'?'待审核': params.row.status === '3'?'报名成功': params.row.status === '4'?'审核未通过':'待缴费');
            }
          },
          {
            title: '报名时间',
            key: 'createTime',
            render: (h, params) => {
              return h('span',  this.$moment(params.row.createTime).format('YYYY-MM-DD'));
            }
          },
          {
            title: '操作',
            width: this.type === 'event-person'?320:200,
            render: (h, params) => {
              let self = this;
              let statusStr = params.row.payStatus === '1'?'取消缴费':'确认缴费';
              let banStr = params.row.banSatus === '1' ? '取消禁赛':'禁赛';
              let agreeStr = params.row.status === '1'|| params.row.status === '4'? '审核':'取消审核';
              return h('div', [
                h(
                  'Button',
                  {
                    props: {type: 'primary', size: 'small'},
                    style: {marginRight: "5px"},
                    on: {
                      click() {
                        // self.$router.push(`personal-detail/${self.type}/`+ params.row.enrollId);
                        self.$router.push({
                          name:`detail-${self.type}`,
                          params:{
                            type:self.type,
                            enrollId:params.row.enrollId
                          }
                        });
                      }
                    }
                  },
                  '查看资料'
                ),
                this.type === 'event-person'?h(
                  'Poptip',
                  {
                    props: {
                      confirm: true,
                      title: `您确定要${agreeStr}吗?`,
                      transfer: true,
                      placement: 'top'
                    },
                    style: {marginRight: "5px"},
                    on: {
                      'on-ok': () => {
                        let status = agreeStr === '审核'?'3':'4';
                        self.agree(params.row.enrollId,status)
                      }
                    }
                  },
                  [
                    h(
                      params.row.status === '1'||params.row.status === '4'?'Button':null,
                      {
                        style: {
                          marginRight: '5px'
                        },
                        props: {
                          type: 'success',
                          size: 'small'
                        }
                      },
                      agreeStr
                    )
                  ]):null,
                this.type === 'suspension-detail'?h(
                  'Poptip',
                  {
                    props: {
                      confirm: true,
                      title: `您确定要${banStr}这条数据吗?`,
                      transfer: true,
                      placement: 'top'
                    },
                    style: {marginRight: "5px"},
                    on: {
                      'on-ok': () => {
                        self.suspension(params.row.banSatus,params.row.enrollId)
                      }
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        style: {
                          marginRight: '5px'
                        },
                        props: {
                          type: params.row.banSatus === '1' ? 'success' : 'error',
                          size: 'small'
                        }
                      },
                      params.row.banSatus === '1' ? '取消禁赛':'禁赛'
                    )
                  ]
                ):null,
                this.type === 'money-detail'?[h(
                  params.row.payStatus === '1'?'Poptip':'span',
                  {
                    props: {
                      confirm: true,
                      title: `您确定要${statusStr}这条数据吗?`,
                      transfer: true,
                      placement: 'top'
                    },
                    style: {marginRight: "5px"},
                    on: {
                      'on-ok': () => {
                        self.money(params.row.payStatus,params.row.enrollId)
                      }
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        style: {
                          marginRight: '5px'
                        },
                        props: {
                          type: params.row.payStatus === '1' ? 'error' : 'default',
                          size: 'small'
                        },
                        on: {
                          click() {
                            if(params.row.payStatus === '0' || !params.row.payStatus){
                              self.enrollId = params.row.enrollId;
                              self.status = params.row.payStatus;
                              self.visible = true;
                            }
                          }
                        }
                      },
                      params.row.payStatus === '1' ? '取消缴费':'确认缴费'
                    )
                  ]
                ),
                h(
                  'Poptip',
                  {
                    props: {
                      confirm: true,
                      title: `您确定要退费吗?`,
                      transfer: true,
                      placement: 'top'
                    },
                    style: {marginRight: "5px"},
                    on: {
                      'on-ok': () => {
                        self.refund(params.row.enrollId,'1')
                      }
                    }
                  },
                  [
                    h(
                      params.row.retreatStatus === '0'?'Button':'',
                      {
                        style: {
                          marginRight: '5px'
                        },
                        props: {
                          type: 'warning',
                          size: 'small'
                        }
                      },
                      "退费"
                    )
                  ]
                )]:null
              ])
            }
          }
        ],
        tableColumn:[],
        agreeColumn:[],
        type: this.$route.params.type,
        member:[],
        formResult:[],
        sessionColumns:[
          {
            title: "组别",
            field:'group',
            width:200,
            titleAlign: 'center',
            columnAlign:'center',
            isResize:true,
          },
          {
            title: "时间",
            field:'date',
            width:200,
            titleAlign: 'center',
            columnAlign:'center',
            isResize:true,
          },
          {
            title: "发球台",
            field:'table',
            width:200,
            titleAlign: 'center',
            columnAlign:'center',
            isResize:true,
          },
          {
            title: "球员",
            field:'enrollName',
            width:200,
            titleAlign: 'center',
            columnAlign:'center',
            isResize:true,
          },
          {
            field: 'custome-adv',
            title: '操作',
            width:200,
            titleAlign: 'center',
            columnAlign:'center',
            componentName:'table-operation',
            isResize:true,
          }
        ],
        mergeLineArr:[],
        sessionLoading:false,
      }
    },
    mounted() {
      this.model.matchId = this.$route.params.id;
      if(this.type === 'event-person'){
        this.model.type = '1'
      }
      this.tableColumn = this.baseColumn;
      let arr = [{
        type: 'selection',
        width: 60,
        align: 'center'
      }];
      let arrs = {
        title: '配置',
          key:'isConfig',
        render: (h, params) => {
        return h("span",params.row.isConfig === '1'?'已配置':'未配置')
         }
      };
      this.agreeColumn = arr.concat(this.tableColumn);
      this.agreeColumn.splice(14,0,arrs);
      this.query();
      this.queryList();
    },

    methods:{
      query() {
        getOne({matchId: this.model.matchId})
          .then(res => {
            this.container = res;
          });
      },
      queryList() {
        this.loading = true;
        queryListByMatchId(this.model)
          .then(res => {
            this.loading = false;
            let result = res.list;
            this.resultData = result||[];
            this.boyData = result.filter(x => x.sex === '1')||[];
            this.girlData = result.filter(x => x.sex === '2')||[];
          })
      },
      tabClick(name) {
        this.showList = name;
        if(this.type === 'event-person') {
          this.model.type = this.showList === 'apply'?'1': this.showList === 'agree'?'2':'';
          if(this.showList === 'goForm') {
            this.queryForm()
          }
        }
        this.queryList()
      },
      queryForm() {
        this.sessionLoading = true;
        this.mergeLineArr = [];
        this.mergeLineIndex = 0;
        queryForm({matchId:this.model.matchId,type:this.session})
          .then(res => {
            this.sessionLoading = false;
            let arr = []
            res.list.forEach(x => {
              x.memberList.forEach(y => {
                let obj = Object.assign({},y,{
                  date:x.roundDate,
                  time:x.roundTime,
                  group:x.groups,
                  table:x.tables,
                  list:x.memberList.length
                })
                arr.push(obj)
              })
            })
            arr.forEach((res,i) => {
              if (i === 0) {
                this.mergeLineArr.push(1);
                this.mergeLineIndex= 0
              } else {
                // 判断当前元素与上一个元素是否相同,是就给之前相同的第一个+1，并且数组添加一个0
                if (arr[i].group === arr[i - 1].group) {
                  this.mergeLineArr[this.mergeLineIndex] += 1;
                  this.mergeLineArr.push(0);
                } else {//如果与前一个不相同，则追加一个新从1开始的数字，此时更新mergeLineIndex的值
                  this.mergeLineArr.push(1);
                  this.mergeLineIndex= i;
                }
              }
            });
            this.formResult = arr;
            // console.log(this.formResult,'formResult')
          })
      },
      reset() {
        this.$refs["model"].resetFields();
        this.queryList()
      },
      search() {
        this.queryList()
      },
      exportExcel() {
        let param = {
          matchId:this.model.matchId,
          payStatus:this.model.payStatus,
          retreatStatus: this.model.retreatStatus,
          banSatus: this.model.banSatus,
        };
        exportEnrollExcel(param)
          .then(fileUrl => {
            let link = document.createElement('a');
            link.href = fileUrl;
            let suffix = fileUrl.substr(fileUrl.lastIndexOf('.'));
            let name = this.type === 'event-person'?'报名情况详情':this.type === 'money-detail'?'缴费详情':'禁赛详情';
            link.download = this.container.matchName+name;
            link.click();
          })
      },
      suspension(status,id) {
        updateBanStatus({status: status === '1'?'0':'1',enrollId:id})
          .then(res => {
            this.query();
            this.queryList()
          })
      },
      save() {
        if(this.attachment) {
          updatePayUrl({enrollId:this.enrollId,payUrl:this.attachment})
            .then(res => {
              this.queryList();
              this.visible = false;
              this.$refs.upload.fileList = [];
              this.money('0',this.enrollId)
            })
        }else{
          this.$Message.error('请上传缴费凭证');
        }
      },
      money(status,id) {
        updatePayStatus({status:status ==='1'?'0':'1',enrollId:id})
          .then(res => {
            this.queryList()
          })
      },
      refund(id,status) {
        updateRetreatStatus({status:status,enrollId:id})
          .then(res => {
            this.queryList()
          })
      },
      cancel() {
        this.visible =  false;
        this.$refs.upload.fileList = []
      },
      agree(id,status) {
        approvalEnrollStaff({enrollId:id,status:status})
          .then(res => {
            this.queryList()
          })
      },
      // 上传文件成功后发送请求解析
      getFieldData(res, file) {
        if (res.result.retCode === 0) {
          this.attachment = res.data.fileName;
        }else {
          this.$Message.error(res.result.retMessage);
        }
      },
      configGo() {
        if(this.member.length > 0) {
          let configArr = this.member.filter(x => x.isConfig === '1');
          if(configArr.length > 0) {
            this.$Message.warning('含有已配置人员')
          }else {
            this.isSchedule = true;
          }
        }else{
          this.$Message.warning('请选择该赛事配置的出发人员')
        }

      },
      selectChange(selection) {
        this.member = selection;
        this.queryForm()
      },
      handleSpan (rowIndex,rowData,field) {
        if (field === 'group' || field === 'date'|| field === 'table'|| field === 'custome-adv') {
          const _row = this.mergeLineArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            colSpan: _col,
            rowSpan: _row,
            content: field === 'custome-adv'?'':rowData[field],
            componentName:field === 'custome-adv'?'table-operation':'',
          }
        }
      },
      changeSession(e){
        this.session = e;
        this.queryForm()
      },
      del(id) {
        deleteGroup(id)
          .then(res => {
            this.queryForm()
          })
      },
      exportGo() {
        excel({matchId:this.model.matchId,type:this.session})
          .then(fileUrl => {
            let link = document.createElement('a')
            link.href = fileUrl
            let suffix = fileUrl.substr(fileUrl.lastIndexOf('.'))
            let index = +this.session+1
            link.download = this.container.matchName+'第'+index+'出发表配置信息' + suffix
            link.click()
          })
      }
    }
    };
</script>

<style scoped>
  .ivu-form-item{
    margin-bottom: 0 !important;
  }
  .p-info{
    font-size: 16px;
    color: #82868b;
  }
</style>
